package cn.itcast.bos.web.action.take_delivery;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONArray;

import cn.itcast.bos.web.action.common.BaseAction;

@Controller
@Namespace("/")
@ParentPackage("struts-default")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ImageAction extends BaseAction<Object> {
	private File imgFile;
	private String imgFileFileName;
	// 子目录
	private String path;
	// 排序
	private String order;

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	@Action(value = "image_upload")
	public void imageUpload() {
		ServletActionContext.getResponse().setCharacterEncoding("utf-8");
		String realPath = ServletActionContext.getServletContext().getRealPath("upload");
		// 生产随机不重复文件名
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String fileName = uuid + imgFileFileName.substring(imgFileFileName.lastIndexOf('.'));
		// 文件目录分离算法
		int h1 = fileName.hashCode();
		int d1 = h1 & 0xf;
		int h2 = h1 >>> 4;
		int d2 = h2 & 0xf;
		String path = "/" + d1 + "/" + d2 + "/";
		File filePath = new File(realPath, path);
		// 判断目录是否存

		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		File file = new File(filePath, fileName);
		try {
			// 复制文件
			FileUtils.copyFile(imgFile, file);
			// 创建响应数据
			Map<String, Object> map = new HashMap<>();
			map.put("error", 0);
			map.put("url", ServletActionContext.getRequest().getContextPath() + "/upload" + path + fileName);
			String json = JSONArray.toJSONString(map);
			ServletActionContext.getResponse().getWriter().write(json);
		} catch (Exception e) {
			Map<String, Object> map = new HashMap<>();
			map.put("error", 1);
			map.put("message", "上传失败");
			String json = JSONArray.toJSONString(map);
			try {
				ServletActionContext.getResponse().getWriter().write(json);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}

	// 图片空间,显示服务器所有文件,已经用json.jsp插件代替
	@Action(value = "image_manage")
	public void imageManage() {
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		// 文件类型
		String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
		// 获得绝对路径 D:/xxx/upload/
		String rootPath = ServletActionContext.getServletContext().getRealPath("/") + "upload/";
		// 获得绝对url localhost:8080/xxx/upload/
		String rootUrl = ServletActionContext.getRequest().getContextPath() + "/upload/";
		path = path != null ? path : "";
		// 拼接子路径
		String currentPath = rootPath + path;
		String currentUrl = rootUrl + path;
		String currentDirPath = path;
		// 获得上一级目录
		System.err.println(currentPath);
		String moveupDirPath = "";
		if (!"".equals(path)) {
			String str = currentDirPath.substring(0, currentDirPath.length() - 1);
			moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
		}
		// 排序
		order = order != null ? order.toLowerCase() : "name";
		// 遍历当前目录,获得一个装有map的集合
		File currentPathFile = new File(currentPath);
		List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();
		if (currentPathFile.listFiles() != null) {
			for (File file : currentPathFile.listFiles()) {
				Map<String, Object> map = new HashMap<String, Object>();
				String fileName = file.getName();
				if (file.isDirectory()) {
					map.put("is_dir", true);
					map.put("has_file", (file.listFiles() != null));
					map.put("filesize", 0L);
					map.put("is_photo", false);
					map.put("filetype", "");
				} else if (file.isFile()) {
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					map.put("is_dir", false);
					map.put("has_file", false);
					map.put("filesize", file.length());
					map.put("is_photo", Arrays.<String> asList(fileTypes).contains(fileExt));
					map.put("filetype", fileExt);
				}
				map.put("filename", fileName);
				map.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
				fileList.add(map);
			}
		}
		// if ("size".equals(order)) {
		// Collections.sort(fileList, new SizeComparator());
		// } else if ("type".equals(order)) {
		// Collections.sort(fileList, new TypeComparator());
		// } else {
		// Collections.sort(fileList, new NameComparator());
		// }
		// 创建响应数据
		Map<String, Object> result = new HashMap<>();
		result.put("moveup_dir_path", moveupDirPath);
		result.put("current_dir_path", currentDirPath);
		result.put("current_url", currentUrl);
		result.put("total_count", fileList.size());
		result.put("file_list", fileList);
		String json = JSONArray.toJSONString(result);
		try {
			ServletActionContext.getResponse().getWriter().write(json);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
